package com.kilomob.grady.spring;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.event.ContextRefreshedEvent;

import com.kilomob.grady.client.netty.NettyClient;

/**
 * 
 * client解析类
 * 
 *   
 * @author zhouzhixiang  
 * @date 2016年12月31日 
 * @since 1.0
 */
public class ClientBean implements InitializingBean {
    private transient volatile boolean initialized;
    private String id;
    private String address;
    private String name;
    private String protocol;
    private Integer connections;
    // 远程调用超时时间(毫秒)
    private Integer timeout;
    
    private boolean reconnect;
    

    public void afterPropertiesSet() throws Exception  {
        init();
    }
    
    public void init() throws Exception {
        String[] str = address.split(":");
        NettyClient client = new NettyClient();
        client.setId(id);
        client.setName(name);
        client.setTimeout(timeout);
        client.setConnections(connections);
        client.setReconnect(reconnect);
        client.connect(str[0], Integer.parseInt(str[1]), protocol);
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Integer getConnections() {
        return connections;
    }

    public void setConnections(Integer connections) {
        this.connections = connections;
    }

    public Integer getTimeout() {
        return timeout;
    }

    public void setTimeout(Integer timeout) {
        this.timeout = timeout;
    }
    
    
    
    public boolean isReconnect() {
        return reconnect;
    }

    public void setReconnect(boolean reconnect) {
        this.reconnect = reconnect;
    }

    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            if(!initialized){
                init();
            }
            initialized = true;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    
    
    
}


